<template>
  <h2>vue-pdf插件pdf预览效果</h2>
  <div class="pdf">
    <div class="pdf-tab">
      <!--页签展示 -->
      <!--
      <div
        v-for="(item,index) in pdfList" 
        :key="index"
        :class="['btn-def',{'btn-active':activeIndex === index}]"
        @click.stop="pdfClick(item.pdfUrl,index)"
      >
        {{ item.title }}
      </div>
      -->
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-arrow-left"
          size="mini"
          @click="prePage"
        >
          上一页
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-arrow-right el-icon-right"
          size="mini"
          @click="nextPage"
        >
          下一页
        </el-button>
      </el-button-group>
      <div>{{ pageNum }} / {{ numPages }}</div>
      <pdf
        :page="pageNum"
        :src="pdfUrl"
        @progress="loadedRatio = $event"
        @num-pages="numPages = $event"
      />
    </div>
  </div>
</template>
<script>
// 参考文章 https://www.cnblogs.com/douyage/p/12882995.html
import { defineComponent,reactive,ref,onBeforeMount,getCurrentInstance } from "vue"
import pdf from "vue-pdf"
export default defineComponent({
  name:"DymicPdf",
  components:{
    pdf
  },
  setup() {
    const pdfList = reactive([
      {
        pdfUrl: "http://file.gp58.com/file/2018-11-14/111405.pdf",
        title: "中信证券观点"
      },
      {
        pdfUrl:
          "https://dakaname.oss-cn-hangzhou.aliyuncs.com/file/2018-12-28/1546003237411.pdf",
        title: "12月投资月刊"
      }
    ])
    const pdfUrl = ref("http://file.dakawengu.com/file/2018-05-29/20180527-tianfeng.pdf")
    const numPages = ref(1)
    let pageNum = ref(1)
    let loadedRatio = ref(0) // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了

    const pdfClick = (pdfUrl,index) => {
      if(index === activeIndex.value) return
      activeIndex.value = index
      pdfUrl = null
      pdfTask(pdfUrl)
    }

    const pdfTask = (pdfUrl) => {
      let loadingTask = pdf.createLoadingTask(pdfUrl)
      loadingTask.promise.then(pdf => {
        pdfUrl = loadingTask
        // numPages = pdf.numPages
      }).catch(err => {
        console.error("pdf加载失败")
      })
    }

    const prePage = () => {
      let page = pageNum
      page = page > 1 ? page - 1 : numPages
      pageNum = page
    }

    const nextPage = () => {
      let page = pageNum
      page = page < numPages.value ? page + 1 : 1
      pageNum = page
    }

    onMount(() => {
      // pdfTask(pdfList[0].pdfUrl)
    })

    return {
      pdfList,pdfUrl,numPages,activeIndex,
      pdfClick,
      prePage,
      nextPage,
      pageNum,
      loadedRatio,
      pdfTask
    }
  }
})
</script>
<style lang='less' scoped>

</style>